/**
 * hmappscripts.js
 * 
 * Common library for history-manager program logic
 * 
 * Author:  Thomas Aulich
 * Version: 1.0
 */

/**
 * Globals ...
 */
var global_show_legend = true;
var global_zoom_y = true;
var global_zoom_x = true;

/**
 * Array of cached TimeSeries-Objects
 */
var timeSeries = [];

/**
 * Array of cached measurePoints
 */
var measurePoints = [];

/**
 * "Class"-definition for TimeSeries-objetcs
 */
function TimeSeries(series) {
	// alert("Series " + series.label + " Color: " + series.id);
	this.label = series.label;
	this.data = series.data;
	this.color = series.id;
	this.id = series.id;
	this.measurePoint = series.measurePoint;
	this.unit = series.unit;
	this.size = series.size;
	this.active = true;
}

/**
 * "Class"-definition for MeasurePointList-objects
 */
function MeasurePointListDefinition(id, name, data) {
	this.id = id;
	this.name = name;
	this.measurePointIds = data;
}

/**
 * "Class"-definition for CSVDownLoadRequest-objects
 */
function CSVDownLoadDefinition(datefrom, dateto, data) {
	this.datefrom = datefrom;
	this.dateto = dateto;
	this.measurePointIds = data;
}

/**
 * Method to load the array of measurepoints (measurePoints[]) with data from
 * AJAX-response
 * 
 * @param points
 */
function registerMeasurePoints(points) {
	// Clear "old" array (if exists...)
	measurePoints = [];
	for (var i = 0; i < points.length; i++) {
		measurePoints.push(points[i]);
	}
	buildMeasurePointChoicesUI();
	plotAccordingToChoices();
}

/**
 * Event-Handler for several purpose click events...
 */
function multiPurposeClickEventHandler() {
	var uiObject = this;
	if (uiObject.id == "legendCheckBox") {
		global_show_legend = uiObject.checked;
		drawDiagram();
	}
	if (uiObject.id == "zoomXCheckBox") {
		global_zoom_x = uiObject.checked;
		drawDiagram();
	}
	if (uiObject.id == "zoomYCheckBox") {
		global_zoom_y = uiObject.checked;
		drawDiagram();
	}
	if (uiObject.id == "butReload") {
		reloadAllTimeSeries();
	}
	if (uiObject.id == "butMPLSave") {
		sendSaveMeasurePointListRequest();
	}
	if (uiObject.id == "butMPLDelete") {
		sendDeleteMeasurePointListRequest();
	}
	if (uiObject.id == "butMPLNew") {
		sendSaveMeasurePointListRequest("new");
	}
	if (uiObject.id == "butExport") {
		sendCSVDownLoadRequest();
	}
}

/**
 * Method to create TimeSeries Object and register/replace in timeSeries-array
 */
function registerTimeSeries(series) {
	var id = series.id;
	var i = 0;
	var allReadyRegistered = false;
	// Loop through all elements of timeSeries and remove series
	// there, if found ...
	while (i < timeSeries.length && !allReadyRegistered) {
		if (timeSeries[i].id == id) {
			allReadyRegistered = true;
		} else {
			i++;
		}
	}
	// Replace series or push on top of stack when new
	if (allReadyRegistered) {
		timeSeries[i] = new TimeSeries(series);
	} else {
		timeSeries.push(new TimeSeries(series));
	}
	// (re)draw the diagram...
	drawDiagram();
}

/**
 * Method to activate or deactivate a chached TimeSeries
 * 
 * @param id
 * @param trueORfalse
 */
function setTimeSeriesActive(id, trueORfalse) {
	var i = 0;
	var done = false;
	while (i < timeSeries.length && !done) {
		if (timeSeries[i].id == id) {
			timeSeries[i].active = trueORfalse;
			done = true;
		} else {
			i++;
		}
	}
}

/**
 * Draws diagram based on the global timeSeries[]-array
 */
function drawDiagram() {
	var options = {
		lines : {
			show : true
		},
		points : {
			show : false
		},
		xaxis : {
			mode : "time",
			panRange : global_zoom_x,
			zoomRange : global_zoom_x
		},
		yaxis : {
			panRange : global_zoom_y,
			zoomRange : global_zoom_y
		},
		zoom : {
			interactive : true
		},
		pan : {
			interactive : true
		},
		legend : {
			show : global_show_legend
		},
		colors : [ "#FF0000", "#FF8000", "#FFFF00", "#80FF00", "#00FFFF",
				"#0000FF", "#FF00FF", "#808080", "#FF9999", "#000000"]
	};
	activedata = [];
	// Loop around all TimeSeries in timeSeries
	// and push active ones to data[]
	for (var i = 0; i < timeSeries.length; i++) {
		if (timeSeries[i].active) {
			activedata.push(timeSeries[i]);
		}
	}
	$.plot("#placeholder", activedata, options);
}

/**
 * Method sends AJAX-request to get TimeSeries-data
 * 
 * @param id
 */
function sendTimeSeriesRequest(id) {
	var dateFrom = $("#dateFrom").datepicker('getDate');
	var dateTo = $("#dateTo").datepicker('getDate');
	var dataurl = 'DataProvider?mode=getmeasure&measurepointid=' + id;
	if (dateFrom != null) {
		dataurl = dataurl + '&datefrom=' + getMyISOString(dateFrom);
	}
	if (dateTo != null) {
		dataurl = dataurl + '&dateto=' + getMyISOString(dateTo);
	}
	$.ajax({
		url : dataurl,
		type : "GET",
		dataType : "json",
		success : registerTimeSeries
	});
}

/**
 * Method sends AJAX-request to get MeasurePoint-data for ALL MeasurePoints in
 * the database...
 * 
 * @param id
 */
function sendMeasurePointRequest() {
	var dataurl = 'DataProvider?mode=getmeasurepoint';
	$.ajax({
		url : dataurl,
		type : "GET",
		dataType : "json",
		success : registerMeasurePoints
	});
}

/**
 * Method sends AJAX-request to get MeasurePoint-data for ALL MeasurePoints in
 * the database...
 * 
 * @param id
 */
function sendMeasurePointListRequest() {
	var dataurl = 'DataProvider?mode=getmeasurepointlist';
	$.ajax({
		url : dataurl,
		type : "GET",
		dataType : "json",
		beforeSend : function() {
			$("#mplist").selectmenu('disable');
		},
		success : function(response) {
			$('#mplist').html('');
			$.each(response, function(i, data) {
				$('#mplist').append(
						$("<option></option>").attr("value", data.id).text(
								data.name));
			});
			$('#mplist').selectmenu('destroy').selectmenu();
			$("#mplist").selectmenu('enable');
			var id = $("#mplist").val();
			sendMeasurePointListLinkRequest(id);
		}
	});
}

/**
 * Method sends AJAX-request to get MeasurePointListLink-information for a
 * specified MeasurePointList (id-parameter)
 * 
 * @param id
 */
function sendMeasurePointListLinkRequest(id) {
	if (id != null) {
		var dataurl = 'DataProvider?mode=getmeasurepointlistlink&id=' + id;
		$.ajax({
			url : dataurl,
			type : "GET",
			dataType : "json",
			beforeSend : function() {
			},
			success : function(response) {
				// At first all inputs have to be unchecked again
				// var choiceContainer = $("#southwest");
				// choiceContainer.find("input").each(function() {
				// $(this).attr('checked', false);
				// $(this).checkboxradio('refresh');
				// });
				// (Re)-build the checkboxes in the choiceContainer
				buildMeasurePointChoicesUI();
				// Next: deactivate all cached timeseries
				for (var i = 0; i < timeSeries.length; i++) {
					timeSeries[i].active = false;
				}
				// Now mark all inputs that are retrieved as checked
				// also activate the corresponding timeseries
				$.each(response, function(i, data) {
					var id = "#id" + data;
					var checkbox = $(id);
					checkbox.attr('checked', true);
					// checkbox.checkboxradio('refresh');
					setTimeSeriesActive(data, true);
				});
				plotAccordingToChoices();
			}
		});
	}
}

/**
 * Method adds checkboxes for all registered MeasurePoints (array measurePoints)
 */
function buildMeasurePointChoicesUI() {
	var choiceContainer = $("#southwest");
	choiceContainer.empty();
	choiceContainer.append("<table>");
	for (var i = 0; i < measurePoints.length; i++) {
		choiceContainer.append("<tr><td><input type='checkbox' name='"
				+ measurePoints[i].id + "' id='id" + measurePoints[i].id
				+ "'></input></td>" + "<td><label for='id"
				+ measurePoints[i].id + "'>" + measurePoints[i].aliasName
				+ "</label></td></tr>");
	}
	choiceContainer.append("</table>");
	choiceContainer.find("input").click(plotAccordingToChoices);
}

/**
 * Checks, if a specific TimeSeries (given by id) is registered or not
 * 
 * @param id
 */
function isTimeSeriesRegistered(id) {
	var i = 0;
	var found = false;
	while (i < timeSeries.length && !found) {
		if (timeSeries[i].id == id) {
			found = true;
		} else {
			i++;
		}
	}
	return found;
}

/**
 * Eventhandler-function, that is called whenever a MeasurePoint-Checkbox is
 * clicked ...
 */
function plotAccordingToChoices() {
	var choiceContainer = $("#southwest");
	choiceContainer.find("input").each(function() {
		var id = $(this).attr("name");
		var checked = this.checked;
		if (checked) {
			if (!isTimeSeriesRegistered(id)) {
				sendTimeSeriesRequest(id);
			}
		}
		setTimeSeriesActive(id, checked);
	});
	drawDiagram()
}

/**
 * Getting formatted ISO-date without any influence of browsers time-zone
 * Format: 'yyyy-mm-dd'
 * 
 * @param date
 * @returns {String}
 */
function getMyISOString(mydate) {
	function pad(number) {
		if (number < 10) {
			return '0' + number;
		}
		return number;
	}
	return mydate.getFullYear() + '-' + pad(mydate.getMonth() + 1) + '-'
			+ pad(mydate.getDate());
}

/**
 * Reloads all TimeSeries in timeSeries[] based on current selections
 */
function reloadAllTimeSeries() {
	timeSeries = [];
	plotAccordingToChoices();
}

/**
 * Sends a post-request along to the serfer to save the currently selected
 * measurepointlist
 */
function sendSaveMeasurePointListRequest(mode) {
	var id = $("#mplist").val();
	if (id == null) {
		// if there is no option selected this MUST
		// be 'new'-mode
		mode = "new";
	} else {
		// if there is no mode defined default mode is
		// 'update'
		if (mode == null) {
			mode = 'update';
		} else {
			// Check if mode is valid ('new' or 'update')
			if (mode != 'save' && mode != 'update' && mode != 'new')
				mode = 'update';
		}
	}
	// if mode = 'new': ask the user for the name...
	var name = "";
	if (mode == 'new') {
		while (name.trim() == "") {
			name = prompt(
					"Bitte geben Sie einen Namen für die neue Messpunktgruppe ein!",
					" ");
			// Check, if user aborts the process...
			if (name == null || name == '')
				return;
		}
		name = name.trim();
		id = null;
	}
	var mpids = [];
	var choiceContainer = $("#southwest");
	choiceContainer.find("input").each(function() {
		var id = $(this).attr("name");
		var checked = this.checked;
		if (checked) {
			mpids.push(id);
		}
	});
	var measurePointListDefinition = new MeasurePointListDefinition(id, name,
			mpids);
	var dataurl = 'DataProvider?mode=setmeasurepointlist';
	$
			.ajax({
				type : "POST",
				url : dataurl,
				data : {
					"data" : JSON.stringify(measurePointListDefinition)
				},
				success : function(data) {
					sendMeasurePointListRequest();
				},
				error : function(data) {
					alert("Beim Speichern der Messpunktgruppe ist ein Fehler aufgetreten!");
				}
			});
}

/**
 * Sends a get-request along to the serfer to delete the currently selected
 * measurepointlist
 */
function sendDeleteMeasurePointListRequest() {
	var id = $("#mplist").val();
	if (id != null) {
		var dataurl = 'DataProvider?mode=deletemeasurepointlist&id=' + id;
		$
				.ajax({
					type : "GET",
					url : dataurl,
					success : function(data) {
						alert('Messpunktgruppe erfolgreich gelöscht.');
						sendMeasurePointListRequest();
					},
					error : function(data) {
						alert("Beim Löschen der Messpunktgruppe ist ein Fehler aufgetreten!");
					}
				});
	}
}
/**
 * Method sends AJAX-request to get data in CSV-format
 */
function sendCSVDownLoadRequest() {
	var dataurl = 'DataProvider?mode=getcsvdownload';
	var dateFrom = $("#dateFrom").datepicker('getDate');
	var dateTo = $("#dateTo").datepicker('getDate');
	if (dateFrom != null) {
		dataurl = dataurl + '&datefrom=' + getMyISOString(dateFrom);
	}
	if (dateTo != null) {
		dataurl = dataurl + '&dateto=' + getMyISOString(dateTo);
	}
	var idList = "";
	var choiceContainer = $("#southwest");
	choiceContainer.find("input").each(function() {
		var id = $(this).attr("name");
		var checked = this.checked;
		if (checked) {
			if (idList == "") {
				idList = id;
			} else {
				idList += "," + id;
			}
		}
	});
	idList = "(" + idList + ")";
	dataurl = dataurl + "&idlist=" + idList;
	/*
	 * $.ajax({ type : "GET", url : dataurl, success : function(data) {
	 * alert('Downloadsuccess'); }, error : function(data) { alert("Beim Abruf
	 * der CSV-Daten ist ein Fehler aufgetreten!"); } });
	 */
	window.open(dataurl, '_blank');
}